package com.dhb.pattern.proxy.dynamicproxy.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 功能描述：
 * 创建人：citymoon
 * 创建日期：2019/5/12
 */
public class CglibProxy implements MethodInterceptor {

    public Object getInstance(Class<?> clazz) throws Exception{
        //1.相当于Proxy，代理的工具类
        Enhancer enhancer = new Enhancer();
        //2.设置父类
        enhancer.setSuperclass(clazz);
        //3.设置回调函数
        enhancer.setCallback(this);
        //4.创建子类(代理对象)
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object object = methodProxy.invokeSuper(o, objects);
        after();
        return object;
    }

    private void after() {
        System.out.println("自我介绍");
    }

    private void before() {
        System.out.println("感谢观众");
    }
}
